
package com.lancoo.tyjx.multichatroom.view;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;

import com.lancoo.tyjx.multichatroom.R;
import com.lancoo.tyjx.multichatroom.constants.Constants;
import com.lancoo.tyjx.multichatroom.utils.Tool;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.IOException;

import io.reactivex.functions.Consumer;


@SuppressLint("NewApi")
public class RecordButton extends android.support.v7.widget.AppCompatTextView {

    //	private RxPermissions rxPermissions;
    private static final String TAG = "RecordButton";
    private AppCompatActivity mActivity;
    private long startMills;
    private long endMills;

    private String mFileName = null;
    private OnFinishedRecordListener finishedListener;
    private static long startTime;
    private Dialog recordIndicator;
    private static int[] res = {R.drawable.micro_2_new, R.drawable.micro_3_new,
            R.drawable.micro_4_new, R.drawable.micro_5_new};
    private static ImageView view;
    private static TextView duraView;
    private MediaRecorder recorder;
    private ObtainDecibelThread thread;
    private Handler volumeHandler;
    private static final int MIN_INTERVAL_TIME = 1 * 1000;// 2s 最短
    public final static int MAX_TIME = 60 * 1000 + 500;// 20秒，最长
    private final String SAVE_PATH = Constants.SAVE_SOUND_PATH;

    private float y;
    private boolean mReady = false;
    private boolean iswantToCancel = false;
    private static final int DISTANCE_Y_CANCEL = 50;
    private RxPermissions rxPermissions;

    public RecordButton(Context context) {
        super(context);
        init();
    }

    public RecordButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public RecordButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void setSavePath(String path) {
        File filePath = new File(path);
        if (!filePath.exists()) {
            File file2 = new File(path.substring(0, path.lastIndexOf("/") + 1));
            file2.mkdirs();
        }
        mFileName = path;
    }

    public void setOnFinishedRecordListener(OnFinishedRecordListener listener) {
        finishedListener = listener;
    }

    private void init() {
        volumeHandler = new ShowVolumeHandler();

        setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (null == rxPermissions) {
                    rxPermissions = new RxPermissions(mActivity);
                }
                startMills = System.currentTimeMillis();
                rxPermissions
                        .request(Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(new Consumer<Boolean>() {
                            @Override
                            public void accept(Boolean granted) throws Exception {
                                if (granted) { // Always true pre-M
                                    endMills = System.currentTimeMillis();
                                    if (endMills - startMills < 500) {
                                        mReady = true;
                                        initDialogAndStartRecord();
                                        startRecording();
                                        startMills = System.currentTimeMillis();
                                    }
                                }
                            }
                        });
                return false;
            }
        });
    }

    public void setActivity(AppCompatActivity fragmentActivity) {
        mActivity = fragmentActivity;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        y = event.getY();
//		if(y<0)
//        {
//            iswantToCancel = true;
//            recorder.pause();
//            view.setImageResource(R.drawable.mic_cancel);
//        }


        switch (action) {
            case MotionEvent.ACTION_DOWN:
                setText("松开发送");
//			initDialogAndStartRecord();
//			startMills = System.currentTimeMillis();
                break;
            case MotionEvent.ACTION_UP:
                Log.i(TAG, "onTouchEvent: ACTION_UP");
                if (!mReady) {   //没有触发onLongClick
                    reset();
                    return super.onTouchEvent(event);
                }
                this.setText("按住录音");
                if (y >= 0 && (System.currentTimeMillis() - startTime <= MAX_TIME)) {
                    finishRecord();
                } else if (y < 0) {  //当手指向上滑，会cancel
                    cancelRecord();
                }
                iswantToCancel = false;
                break;
            case MotionEvent.ACTION_MOVE:
                if (mReady) {
                    int x = (int) event.getX();       //获取当前的坐标
                    int y = (int) event.getY();
                    if (!iswantToCancel && wantToCancel(x, y)) {
                        Log.i(TAG, "onTouchEvent: ACTION_MOVE");
                        iswantToCancel = true;
//					recorder.stop();
                        view.setImageResource(R.drawable.mic_cancel_new);
                    }
                }
                break;
            case MotionEvent.ACTION_CANCEL: // 异常
                cancelRecord();
                break;
        }

        return super.onTouchEvent(event);
    }

    private boolean wantToCancel(int x, int y) {
        // 判断手指的滑动是否超出范围
        if (x < 0 || x > getWidth()) {
            return true;
        }
        if (y < -DISTANCE_Y_CANCEL || y > getHeight() + DISTANCE_Y_CANCEL) {
            return true;
        }
        return false;
    }

    private void reset() {
        cancelRecord();
        iswantToCancel = false;
        mReady = false;
        this.setText("按住录音");
    }

    private void initDialogAndStartRecord() {
        startTime = System.currentTimeMillis();
        recordIndicator = new Dialog(getContext(),
                R.style.like_toast_dialog_style);
        view = new ImageView(getContext());
        view.setImageResource(R.drawable.micro_2_new);
        recordIndicator.setContentView(view, new LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));

        duraView = new TextView(getContext());
        duraView.setTextColor(getResources().getColor(R.color.white));
        duraView.setText("  0\"  最长20\"");
        duraView.setTextSize(15);
        recordIndicator.addContentView(duraView, new LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));

//		recordIndicator.setOnDismissListener(onDismiss);
        LayoutParams lp = recordIndicator.getWindow().getAttributes();
        lp.gravity = Gravity.CENTER;

//		startRecording();
        recordIndicator.show();
    }

    private void finishRecord() {
        mReady = false;
        stopRecording();
        recordIndicator.dismiss();

        long intervalTime = System.currentTimeMillis() - startTime;
        if (intervalTime < MIN_INTERVAL_TIME) {
            Tool.initToast(getContext(), "时间太短！");
            File file = new File(mFileName);
            file.delete();
            return;
        }

        if (finishedListener != null)
            finishedListener.onFinishedRecord(mFileName, (int) (intervalTime / 1000));
    }

    public void cancelRecord() {
        stopRecording();
        if (recordIndicator != null) {
            recordIndicator.dismiss();
        }
//		MyToast.makeText(getContext(), "取消录音！", Toast.LENGTH_SHORT);
        if (mFileName != null) {
            File file = new File(mFileName);
            file.delete();
        }
        iswantToCancel = false;
        mReady = false;
    }

    private void startRecording() {
        if (null != finishedListener) {
            finishedListener.onStartRecord();
        }

        // save path
        StringBuilder path = new StringBuilder(SAVE_PATH)
                .append("/tmp_sound_").append(System.currentTimeMillis()).append(".amr");
        setSavePath(path.toString());
        recorder = new MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setAudioChannels(1);
        recorder.setAudioEncodingBitRate(4000);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        //recorder.setVideoFrameRate(4000);
        recorder.setOutputFile(mFileName);

        try {
            recorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }

        recorder.start();
        thread = new ObtainDecibelThread();
        thread.start();
        Vibrator vib = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);  //震动提醒
        vib.vibrate(100);
    }

    private void stopRecording() {
        Log.i(TAG, "stopRecording: ");
        if (thread != null) {
            thread.exit();
            thread = null;
        }
        if (recorder != null) {
            recorder.stop();
            recorder.release();
            recorder = null;
        }
    }

    private class ObtainDecibelThread extends Thread {

        private volatile boolean running = true;

        public void exit() {
            running = false;
        }

        @Override
        public void run() {
            while (running) {
                if (recorder == null || !running) {
                    break;
                }
                if (iswantToCancel) {
                    continue;
                }
                int x = recorder.getMaxAmplitude();
                if (x != 0 && y >= 0) {
                    int f = (int) (10 * Math.log(x) / Math.log(10));
                    if (f < 26) {
                        volumeHandler.sendEmptyMessage(0);
                    } else if (f < 32) {
                        volumeHandler.sendEmptyMessage(1);
                    } else if (f < 38) {
                        volumeHandler.sendEmptyMessage(2);
                    } else {
                        volumeHandler.sendEmptyMessage(3);
                    }
                }

                volumeHandler.sendEmptyMessage(-1);
                if (System.currentTimeMillis() - startTime > MAX_TIME) {
                    finishRecord();
                }

                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private OnDismissListener onDismiss = new OnDismissListener() {

        @Override
        public void onDismiss(DialogInterface dialog) {
            stopRecording();
        }
    };

    static class ShowVolumeHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == -1) {
                duraView.setText("  " + (System.currentTimeMillis() - startTime) / 1000 + "\"  最长60\"");
            } else {
                view.setImageResource(res[msg.what]);
            }
        }
    }

    public interface OnFinishedRecordListener {
        void onStartRecord();

        void onFinishedRecord(String audioPath, int time);
    }
}
